﻿using System.Linq.Expressions;
using CommunityToolkit.Mvvm.ComponentModel;//Nuget安装 CommunityToolkit.mvvm
using CommunityToolkit.Mvvm.Input;
using DailyPoetryM.Models;
using DailyPoetryM.Services;
using TheSalLab.MauiInfiniteScrolling;//nuget 安装TheSalLab.MauiInfiniteScrolling

//展示搜索结果页面
namespace DailyPoetryM.VieModels;

public class ResultPageViewModel : ObservableObject
{

    // 使用一个可绑定的属性来接收搜索条件 ：查询语句
    /// <summary>
    /// 查询语句。
    /// </summary>
    public Expression<Func<Poetry, bool>> Where
    {
        get => _where;
        set => _canLoadMore = SetProperty(ref _where, value);
    }
    private Expression<Func<Poetry, bool>> _where;



    //结果从数据库取出显示到界面上，且支持无限滚动
    /// <summary>
    /// 诗词集合。
    /// </summary>
    public MauiInfiniteScrollCollection<Poetry> Poetries { get; }//无限滚动集合

    /// <summary>
    /// 诗词存储。
    /// </summary>
    private IPoetryStorage _poetryStorage;

    /// <summary>
    /// 搜索结果页ViewModel。
    /// </summary>
    /// <param name="poetryStorage">诗词存储。</param>
    /// 
    public ResultPageViewModel(IPoetryStorage poetryStorage)
    {
        Poetries = new MauiInfiniteScrollCollection<Poetry>     //自己的数据
        {
            OnCanLoadMore = () => _canLoadMore,
            //onclick  means Button.Clicked OnbuttonClicked
            OnLoadMore = async () =>{
                Status = Loading;           //加载的信息为：正在载入
                                            //poetries接收返回的结果，数据库的数据
                                            //poetryStorage.GetPoetriesAsync（1,2,3）读数据函数，传递三个条件：where、Poetries.Count（跳过的结果数）、 PageSize（返回多少条）
                                            //ToList()：变成列表
                var poetries = (await poetryStorage.GetPoetriesAsync(Where, Poetries.Count, PageSize)).ToList();
                //调用GetPoetriesAsync()获得诗词集合
                //PoetryCollection里有多少条就跳过这些有的继续加载，返回页面PageSize个

                Status = string.Empty;

                if (poetries.Count < PageSize){
                    //没有更多结果了
                    _canLoadMore = false;
                    Status = NoMoreResult;
                }

                if (Poetries.Count == 0 && poetries.Count == 0){
                    _canLoadMore = false;
                    Status = NoResult;
                }
                return poetries;
            }
        };
        //当OnCanLoadMore()函数返回值为true时，自动调用OnLoadMore()
        //开始从数据库中读数据
        
        
        // _lazyNavigatedToCommand = new Lazy<AsyncRelayCommand>(() => new AsyncRelayCommand(NavigatedToCommandFunction));

    }



    /// <summary>
    /// 页面显示命令。
    /// </summary>
    /// 
    public RelayCommand _navigatedCommand;
    public RelayCommand NavigatedCommand =>
    _navigatedCommand ?? (_navigatedCommand = new RelayCommand(async () => await NavigatedToCommandFunction()));

    public async Task NavigatedToCommandFunction(){
        Poetries.Clear();
        _canLoadMore = true; //数据加载进来时将_canLoadMore设置为true（不然一直为false）
        await Poetries.LoadMoreAsync();
    }

    /*
        private Lazy<AsyncRelayCommand> _lazyNavigatedToCommand;

        public AsyncRelayCommand NavigatedToCommand => _lazyNavigatedToCommand.Value;
        public async Task NavigatedToCommandFunction(){
            Poetries.Clear();//清理搜索结果
            await Poetries.LoadMoreAsync();
        }
    */

    //属性
    /// <summary>
    /// Status 加载状态。
    /// </summary>
    public string Status
    {
        get => _status;
        set => SetProperty(ref _status, value);
    }
    private string _status;
    private bool _canLoadMore;                  //能否加载更多结果。
    /// <summary>
    /// 一次显示的诗词数量。
    /// </summary>
    public const int PageSize = 20;             //常量，返回结果数

    //提示信息：常量
    public const string Loading = "正在载入";
    public const string NoResult = "没有满足条件的结果";
    public const string NoMoreResult = "没有更多结果";
}

